#!/usr/bin/env python

import os
f_spot_photo_db = os.path.expanduser("~/.gnome2/f-spot/photos.db")

def get_tag_by_name(con, name):
    cur = con.cursor()
    query = """
    SELECT id
    FROM tags
    WHERE name like "%(name)s"
    """
    cur.execute(query%{'name':name})
    return cur.fetchone()[0]

def get_by_rating(con, min_rating, max_rating=5, tag=None):
    cur = con.cursor()
    if tag == None:
	query = """
	SELECT id, uri, rating 
	%(tag_pattern)s
	    rating >= %(min_rating)i
	    AND
	    rating <= %(max_rating)i
	;
	"""
    else:
	query = """
	SELECT id, uri, rating 
	FROM photos, photo_tags 
	WHERE 
	    photos.id = photo_tags.photo_id
	    AND 
	    tag_id = %(tag)s
	    AND
	    rating >= %(min_rating)i
	    AND
	    rating <= %(max_rating)i
	;
	"""

    tag_pattern = """
    """

    cur.execute(query%{'min_rating':min_rating, 'max_rating':max_rating, 'tag':tag})

    return cur

def main():

    def usage():
	import sys, os
	print """\
usage: %s [options]
       --min		minimum rating (0..5)
       --max		maximum rating (0..5)
    -t --tag <t>	show files with tag name <t>
    -h --help		print this help message
	"""%os.path.basename(sys.argv[0])

    import sqlite3
    con = sqlite3.connect(f_spot_photo_db)
    cur = con.cursor()

    min_rating = 0
    max_rating = 5
    tag = None

    import getopt, sys
    opts, args = getopt.getopt(sys.argv[1:], "t:h", ["min=", "max=", "tag=", "help"])
    for o, a in opts:
	if o in "--min".split():
	    min_rating = int(a)
	elif o in "--max".split():
	    max_rating = int(a)
	elif o in "-t --tag".split():
	    tag = get_tag_by_name(con, a)
	elif o in "-h --help".split():
	    usage()
	    sys.exit()

    for item in get_by_rating(con, min_rating, max_rating, tag):
	print item[1]

if __name__ == '__main__':
    main()
